package com.landary.parameterrplacement.utils;

import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.CDATASection;

import javax.xml.namespace.QName;
import javax.xml.soap.*;

/**
 * @author 刘欣
 * @createTime 2023/8/7 10:08
 * @description
 */
@Slf4j
public class    WebServiceClientUtils {
    public static String getResponseXml(String namespaceUrl,String methodNameStr,String tns,String endpointUrl,String cDATAMessage){
        String responseXml = "";
        try {
            // 创建SOAP连接和消息工厂
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();
            MessageFactory messageFactory = MessageFactory.newInstance();

            // 创建SOAP消息
            SOAPMessage soapMessage = messageFactory.createMessage();
            SOAPPart soapPart = soapMessage.getSOAPPart();
            SOAPEnvelope envelope = soapPart.getEnvelope();
            SOAPBody soapBody = envelope.getBody();

            // 创建方法名SOAPElement
            QName methodName = new QName(namespaceUrl, methodNameStr, tns);
            SOAPElement methodElement = soapBody.addChildElement(methodName);

            // 创建SOAP元素并设置其内容
            SOAPElement soapElement1 = methodElement.addChildElement(envelope.createName("ReqMsg"));
            SOAPElement soapElement2 = soapElement1.addChildElement(envelope.createName("document"));


            // 创建CDATA节点
            CDATASection cdata = soapMessage.getSOAPPart().createCDATASection(cDATAMessage);
            // 将CDATA节点添加到SOAP元素中
            soapElement2.appendChild(cdata);
            // 发送SOAP请求并获取响应
//            String endpointUrl = "http://your-webservice-endpoint-url";
            SOAPMessage soapResponse = soapConnection.call(soapMessage, endpointUrl);
            SOAPBody responseSOAPBody = soapResponse.getSOAPBody();
             responseXml = responseSOAPBody.getTextContent();
//             log.info("webservice请求数据"+responseXml);
            // 关闭连接
            soapConnection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseXml;
    }
}
